package com.wuwei.elearning.websocket;

import com.wuwei.elearning.ELearningApplication;
import com.wuwei.elearning.utils.TrayService;
import com.wuwei.elearning.utils.token.TokenUtil;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;

@Component
@Slf4j
@Service
@ServerEndpoint("/api/websocket/{sid}")
@Data
public class WebSocketServer {
//    //静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。
//    private static int onlineCount = 0;

    //静态变量，用来记录所有在线连接的sid
    private static Set<Long> sids = new HashSet<>();

    //concurrent包的线程安全Set，用来存放每个客户端对应的MyWebSocket对象。
    private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<WebSocketServer>();

    //与某个客户端的连接会话，需要通过它来给客户端发送数据
    private Session session;

    //接收sid
    private Long sid = 0L;



    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("sid") String token) {
        Long account = TokenUtil.getAccountFromToken(token);
        this.session = session;
        webSocketSet.add(this);     //加入set中
        this.sid = account;
        addOnlineCount(account);           //在线数加1
//        TrayService.setToolTip("当前在线人数为："+WebSocketServer.getOnlineCount()+"人。");
    }


    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        subOnlineCount(sid);           //在线数减1
        webSocketSet.remove(this);  //从set中删除

        //断开连接情况下，更新主板占用情况为释放
//        TrayService.setToolTip("当前在线人数为："+WebSocketServer.getOnlineCount()+"人。");
        //这里写你 释放的时候，要处理的业务
    }

    /**
     * 收到客户端消息后调用的方法
     * @ Param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) {

        if ("Pong".equals(message)) {
            log.info("Received Pong from sid: " + sid);
            // 可以在这里更新状态或其他逻辑
            addOnlineCount(sid);
            return;
        }

        //群发消息
        for (WebSocketServer item : webSocketSet) {
            try {
                item.sendMessage(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * @ Param session
     * @ Param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        log.error("发生错误");
        error.printStackTrace();
    }

    public static void sendPingToAll() throws IOException {
        for (WebSocketServer item : webSocketSet) {
            item.sendMessage("Ping");
        }
    }

    /**
     * 实现服务器主动推送
     */
    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }

    /**
     * 群发自定义消息
     */
    public static void sendInfo(String message, @PathParam("sid") Long sid) throws IOException {
        for (WebSocketServer item : webSocketSet) {
            try {
                //这里可以设定只推送给这个sid的，为null则全部推送
                if (sid == null) {
                    item.sendMessage(message);
                } else if (item.sid.equals(sid)) {
                    item.sendMessage(message);
                }
            } catch (IOException e) {
                continue;
            }
        }
    }


    public static synchronized int getOnlineCount() {
        return sids.size();
    }

    public static synchronized void addOnlineCount(Long account) {
        WebSocketServer.sids.add(account);
    }

    public static synchronized void subOnlineCount(Long account) {
        WebSocketServer.sids.remove(account);
    }

    public static CopyOnWriteArraySet<WebSocketServer> getWebSocketSet() {
        return webSocketSet;
    }

}
